package com.wframe.project.jnd.wx.controller;

/**
 * Created by Administrator on 2017/4/18.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.util.DateConvert;
import com.wframe.project.former.enums.OrderStatusEnum;
import com.wframe.project.jnd.rest.util.*;
import com.wframe.project.jnd.services.*;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.vo.PriceBeanVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/we")
public class WeOrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    AddressService addressService;
    @Autowired
    CouponService couponService;
    @Autowired
    PurchaseTempService tempService;

    /**
     * 我的订单页面
     *
     * @return
     */

    @RequestMapping(value = "WeOrderlist")
    public String show(HttpServletResponse response, Model model, String ordercode, String productname, String productcode, String start, String end, String timetype, String psize, String pno, String status, HttpServletRequest request) throws Exception {
        JsonReturn json = new JsonReturn();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            WebUtils.responseWrite(response, json.toErrorString(getClass(), new ClientException(CodeEnum.LoginOut)));
        }
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        model.addAttribute("pageno", pageno);
        model.addAttribute("status", status);
        return "/wesite/view/home/order-list";
    }

    /**
     * 我的订单数据
     *
     * @param model
     * @param ordercode
     * @param productname
     * @param productcode
     * @param start
     * @param end
     * @param timetype
     * @param psize
     * @param pno
     * @param status
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "WeLoadorder")
    public void orderlist(HttpServletResponse response, Model model, String ordercode, String productname, String productcode, String start, String end, String timetype, String psize, String pno, String status, HttpServletRequest request) throws Exception {
        JsonReturn json = new JsonReturn();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            WebUtils.responseWrite(response, json.toErrorString(getClass(), new ClientException(CodeEnum.LoginOut)));
            return;
        }
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        JdataBean parms = new JdataBean();
        parms.put("ordercode", ordercode);
        parms.put("productname", productname);
        parms.put("productcode", productcode);
        parms.put("start", start);
        parms.put("end", end);
        parms.put("backtag", 0);

        Integer readyStatus = null;
        if (StringUtils.trimToEmpty(status).matches("\\d{1,8}")) {
            readyStatus = Integer.parseInt(StringUtils.trimToEmpty(status));
        }
        parms.put("status", readyStatus);
        parms.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        PageResult pr = orderService.queryOrders(parms, pagesize, pageno);
        JdataBean redata = new JdataBean();
        redata.put("orderdata", pr.getList());
        redata.put("pagecount", pr.getPageCount());
        redata.put("resultcount", pr.getResultCount());
        json.putData(redata);
        WebUtils.responseWrite(response, json.toString());
    }

    /**
     * 加载订单详情信息
     *
     * @param ordercode
     * @return
     */
    @RequestMapping(value = "WeLoadorderinfo")
    public String loadorderinfo(String ordercode, HttpSession session, Model model) throws ClientException {
        if (!WebSession.checkLoginStatus(session)) {
            return "/wesite/view/sign/login";

        }
        JdataBean order = orderService.getOrderByCode(ordercode);
        List<Map> productlist = orderService.queryOrderProduct(ordercode);
        model.addAttribute("order", order.getDataMap());
        model.addAttribute("products", productlist);
        return "/wesite/view/home/order-detail";
    }

    /**
     * 进入历史采购
     */
    @RequestMapping(value = "loginHistory")
    public String loginHistory(HttpSession session) {
        if (!WebSession.checkLoginStatus(session)) {
            return "/wesite/view/sign/login";
        }
        return "/wesite/view/order/hislist";
    }

    /**
     * 历史采购
     */
    @RequestMapping(value = "history")
    public void history(String pno, int platform, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {

        JsonReturn json = new JsonReturn();
        int pagesize = 12;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        JdataBean parm = new JdataBean();
        parm.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        parm.put("status", OrderStatusEnum.Sended.getStatus());
        parm.put("platform", platform);
        Date now = new Date();
        parm.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
        parm.put("start", DateConvert.toString(DateConvert.addMonth(now, -6), "yyyy-MM-dd"));
        PageResult pr = orderService.queryOrderProduct(parm, pagesize, pageno);
        json.putData(pr);
        WebUtils.responseWrite(response, json.toString());
    }

    /**
     * 取消订单
     *
     * @param response
     */
    @RequestMapping(value = "WeCancelorder")
    public void cancelorder(String ordercode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            orderService.cancelorder(ordercode, WebSession.getWbUser(session).getUserid());
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 确定收货
     *
     * @param ordercode
     * @param response
     */
    @RequestMapping(value = "WeReceiptGoods")
    public void receiptGoods(String ordercode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            JdataBean order = orderService.getOrderByCode(ordercode);
            if (order.getInt("status") != OrderStatusEnum.Sended.getStatus()) {
                throw new ClientException("该订单已经被处理，请刷新！");
            }
            orderService.receiptGoods(WebSession.getWbUser(session).getUserid(), ordercode);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

   /* *//**
     * 商品直接生成订单
     *
     * @param data
     * @param response
     *//*
    @RequestMapping(value = "WeGenerateorder2")
    public void generateorder2(String data, String type, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (WebSession.getWbUser(session) == null || !WebSession.checkWbUserAuth(session)) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            List<PriceBeanVo> carts = new ArrayList<PriceBeanVo>();
            int amount = 0;
            if ("alloften".equals(type)) {
                //购买全部常购清单商品
                JdataBean parm = new JdataBean();
                parm.put("queryinfo", "false");
                parm.put("userid", WebSession.getWbUser(session).getUserid());
                parm.put("like", data);
                parm.put("canbuy", "true");
                List<Map> list = orderService.queryOften(parm, -1, 1).getList();
                if (list.size() == 0) {
                    throw new ClientException("没有您可购的商品");
                }
                for (Map m : list) {
                    carts.add(new PriceBeanVo(m.get("id").toString(), 1));
                    amount++;
                }
            } else if ("orderbuyagain".equals(type)) {
                //订单再次购买
                List<Map> plist = orderService.queryOrderProduct(data);
                for (Map m : plist) {
                    carts.add(new PriceBeanVo(m.get("id").toString(), Integer.parseInt(m.get("buyamount").toString())));
                    amount++;
                }
            } else if ("panbuy".equals(type)) {
                //购买采购计划
                List<Map> list = tempService.queryPlanProduct(data, null, -1, 1).getList();
                if (list.size() == 0) {
                    throw new ClientException("没有您可购的商品");
                }
                for (Map m : list) {
                    carts.add(new PriceBeanVo(m.get("id").toString(), Integer.parseInt(m.get("buyamount").toString())));
                    amount++;
                }
            } else {
                JSONArray arrs = JSON.parseArray(data);
                if (arrs.size() == 0) {
                    throw new ClientException("请选择商品");
                }
                for (int i = 0; i < arrs.size(); i++) {
                    JdataBean pro = productService.getProductPrice(arrs.getJSONObject(i).getString("priceid"));
                    boolean can = productService.getControlsales(WebSession.getWbUser(session).getUserid(), pro.getString("productid"));//控销
                    if (can) {
                        int num = arrs.getJSONObject(i).getIntValue("num");
                        carts.add(new PriceBeanVo(arrs.getJSONObject(i).getString("priceid"), num));
                        amount += num;
                    }
                }
            }
            if (carts.size() > 0) {
                double freight = 0;//运费
                JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(session).getUserid());
                if (address != null) {
                    freight = orderService.calculateFreight(address.getString("shen"), address.getString("shi"), amount);
                }
                String orderid = orderService.generateorder2(WebSession.getWbUser(session).getUserid(), carts, freight);
                json.putData(orderid);
            } else {
                throw new ClientException("该商品不在您的可购范围");
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }*/

    /**
     * 获取购物车数量
     *
     * @param response
     */
    @RequestMapping(value = "/wegetCartNum")
    public void getCartNum(HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            int num = 0;
            if (WebSession.checkLoginStatus(session)) {
                num = orderService.statCartnum(WebSession.getWbUser(session).getUserid());
            }
            json.putData(num);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入购物车
     *
     * @param session
     */
    @RequestMapping(value = "/weshopcart")
    public String shopcart(HttpSession session, Model model) {
        SessionUser sessionUser = WebSession.getWbUser(session);
        if (sessionUser == null) {
            return "/wesite/view/sign/login";
        }
        model.addAttribute("coupons", couponService.findAvailableCoupons(sessionUser.getUserid(), UserService.UserSourceEnum.WECHAT.ordinal()));
        /*String userid = WebSession.getWbUser(request.getSession()).getUserid();
        List<Map> productlist = orderService.queryCart(userid);
        productService.queryControlsales(userid, productlist);//控销
        productService.queryPricegrade(userid, productlist);//价格等级
        model.addAttribute("list", productlist);*/
        return "/wesite/view/order/cart";
    }

    /**
     * 购物车同步
     */
    @RequestMapping(value = "/syncart")
    public void syncart(String cartId, Integer buycount, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        String userid = WebSession.getWbUser(session).getUserid();
        if (StringUtils.isNotEmpty(cartId) && StringUtils.isNotEmpty(userid) && buycount > 0) {
            orderService.updateCartCount(userid, cartId, buycount);
            HashMap<String, Object> data = new HashMap<String, Object>();
            data.put("userid", userid);
            data.put("cartid", cartId);
            data.put("buycount", buycount);
            data.put("result", "ok");
            json.putData(data);
        }
        WebUtils.responseWrite(response, json.toString());
    }

    //单个商品删除
    @RequestMapping(value = "/wedelCart2")
    public void delCart(String cartid, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            orderService.delCart(WebSession.getWbUser(session).getUserid(), cartid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 购物车商品生成订单
     *
     * @param data
     * @param response
     */
    @RequestMapping(value = "wegenerateorder")
    public void wegenerateorder(String data, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            List<JdataBean> carts = new ArrayList<JdataBean>();
            JSONArray arrs = JSON.parseArray(data);
            if (arrs.size() == 0) throw new ClientException("请选择商品");
            int amount = 0;
            for (int i = 0; i < arrs.size(); i++) {
                int num = Integer.parseInt(arrs.getJSONObject(i).getString("num"));
                if (num <= 0) throw new ClientException("您选择的商品数不正确", "7");
                JdataBean cart = new JdataBean();
                cart.put("cartid", arrs.getJSONObject(i).getString("cartid"));
                cart.put("num", arrs.getJSONObject(i).getString("num"));
                carts.add(cart);
                amount += cart.getInt("num");
            }
            double freight = 0;//运费
            String userid = WebSession.getWbUser(session).getUserid();
            JdataBean address = addressService.getCompanyAddress(userid);
            if (address != null) {
                freight = orderService.calculateFreight(address.getString("shen"), address.getString("shi"), amount);
            }
            String orderid = orderService.wxgenerateorder(userid, carts, freight);
            json.putData(orderid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/wedelCartAll")
    public void delCartAll(@RequestParam("ids[]") String[] ids, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            for (int i = 0; i < ids.length; i++) {
                orderService.delCart(WebSession.getWbUser(session).getUserid(), ids[i]);
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }
}
